//
//  TimerHandler.m
//  HSGProject
//
//  Created by 清正 on 16/8/30.
//  Copyright © 2016年 HSG. All rights reserved.
//

#import "TimerHandler.h"

@implementation TimerHandler

//开启定时器
+ (dispatch_source_t)openTimerEveryTime:(NSTimeInterval)time eventHandler:(void (^)(dispatch_source_t timer))block {
    
    if (time<=0) {
        block(nil);
        return nil;
    }
    
    __block NSTimeInterval evetyTime =time;
    __block dispatch_source_t newTimer;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    newTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(newTimer, dispatch_walltime(NULL,0), evetyTime * NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(newTimer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            block(newTimer);
        });
    });
    dispatch_resume(newTimer);
    return newTimer;
}
//倒计时
+ (dispatch_source_t)countdownSecond:(NSInteger)second eventHandler:(void (^)(dispatch_source_t timer, NSInteger surplusTime))block {
    
    if (second<=0) {
        block(nil, 0);
        return nil;
    }
    
    __block NSInteger timeout =second; //倒计时时间
    __block dispatch_source_t newTimer;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    newTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(newTimer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(newTimer, ^{
        if(timeout<=0) {
            //取消定时器
            dispatch_source_cancel(newTimer); newTimer =nil;
            dispatch_async(dispatch_get_main_queue(), ^{
                block(newTimer, timeout);
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                block(newTimer, (long)timeout);
                timeout--;
            });
        }
    });
    dispatch_resume(newTimer);
    return newTimer;
}

+ (void)performAfterDelay:(NSTimeInterval)time handler:(void (^)(void))newBlock {
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC));
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        newBlock();
    });
}

@end




